using System;
using System.IO;
using System.Net;

namespace kerberosLibs
{
	/// <summary>
	/// Manages updating the kerberos config file by cross checking external ip and
	/// if it has changed re-writing the krb5 conf file.
	/// </summary>
	public class AutoUpdate
	{
		private string _krb_template;
		private string _krb_location;

		/// <summary>
		/// The location of the kerberos file template
		/// </summary>
		public string KRBTemplateLocation 
		{
			get {return _krb_template;}
			set {_krb_template = value;}
		}

		/// <summary>
		/// The location of the krb file we will write out!
		/// </summary>
		public string KRBLocation
		{
			get {return _krb_location;}
			set {_krb_location = value;}
		}

		/// <summary>
		/// Figure out the various locations of things!
		/// </summary>
		public AutoUpdate()
		{
		}

		/// <summary>
		/// The last IP we've written to the output file.
		/// </summary>
		private string _oldIP = "";

		/// <summary>
		/// Determine if we need to update. If so, do it, and return "true"
		/// </summary>
		public bool UpdateIf ()
		{
			///
			/// First, get the old and new IP and see what is up!
			/// 

			string newIP = GetExternalIP();
			bool doUpdate = newIP != _oldIP;

			///
			/// If we are to update, regenerate the conf file!
			/// 

			if (doUpdate) 
			{
				TextReader reader = new StreamReader (_krb_template);
                FileInfo krbOutputFile = new FileInfo(_krb_location);
                if (!krbOutputFile.Directory.Exists)
                {
                    krbOutputFile.Directory.Create();
                }
				TextWriter writer = krbOutputFile.CreateText();

				try 
				{
					string line;
					while ((line = reader.ReadLine()) != null) 
					{
						line = line.Replace ("WHATISMYIP", newIP);
						writer.WriteLine(line);
					}
				} 
				finally 
				{
					reader.Close();
					writer.Close();
				}

				///
				/// Don't do it again until we have to!
				/// 

				_oldIP = newIP;
			}

			return doUpdate;
		}

		/// <summary>
		/// Return the IP address of this machine as seen externally!
		/// </summary>
		/// <returns></returns>
		public string GetExternalIP ()
		{
			WebClient myClient = new WebClient ();
			StreamReader response = new StreamReader (myClient.OpenRead ("http://dynupdate.no-ip.com/ip.php"));
			string data = response.ReadToEnd ();
			response.Close();
			return data;
		}
	}
}
